package org.luxor.commons.redis.client;

import org.luxor.commons.core.utils.Jackson2Utils;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;


/**
 * Redis 对象数据类型
 *
 * @author WangFan
 * @author Mr.Yan  @date 2019/10/8
 * @version 1.1 (GitHub文档: https://github.com/whvcse/RedisUtil )
 */
public class RedisObjectClient extends AbstractRedisClient {

    private ValueOperations<String, String> valueOperations;

    public void setValueOperations(ValueOperations<String, String> valueOperations) {
        Assert.notNull(valueOperations, "valueOperations must be specified");
        this.valueOperations = valueOperations;
    }

    /**
     * 设置缓存
     *
     * @param key   键
     * @param value 值
     */
    public void set(String key, Object value) {
        set(key, value, DEFAULT_EXPIRE_SECOND);
    }

    /**
     * 设置缓存
     *
     * @param key    键
     * @param value  值
     * @param expire 时间(秒) -1代表永不过期
     */
    public void set(String key, Object value, long expire) {
        valueOperations.set(key, Jackson2Utils.toJson(value));
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }

    /**
     * 获取缓存
     *
     * @param key    键
     * @param clazz  类
     * @param expire 时间(秒)
     * @param <T>    类
     * @return
     */
    public <T> T get(String key, Class<T> clazz, long expire) {
        String value = valueOperations.get(key);
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value == null ? null : Jackson2Utils.toBean(value, clazz);
    }

    /**
     * 获取缓存
     *
     * @param key   键
     * @param clazz 类
     * @param <T>   类
     * @return
     */
    public <T> T get(String key, Class<T> clazz) {
        return get(key, clazz, NOT_EXPIRE);
    }

}
